#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

void SeqListInit(SQ* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

void SeqListDestory(SQ* ps)
{
	assert(ps);
	assert(ps->arr);

	free(ps->arr);
	ps->arr = NULL;
	ps->size = ps->capacity = 0;

}

void SeqListCheckCapacity(SQ* ps) 
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SQDataType* tmp = (SQDataType*)realloc(ps->arr,sizeof(SQDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("ralloc fail\n");
			return;
		}
		ps->arr = tmp;
		ps->capacity = newcapacity;
	}
}
void SeqLsitPushFront(SQ* ps, SQDataType x)
{
	SeqListCheckCapacity(ps);

	int end = ps->size;

	while (end >= 0)
	{
		ps->arr[end] = ps->arr[end - 1];
		end--;
	}

	ps->arr[0] = x;
	ps->size++;

}
void SeqListPushBack(SQ* ps, SQDataType x)
{
	SeqListCheckCapacity(ps);

	ps->arr[ps->size] = x;
	ps->size++;
}


int SeqListFind(SQ* ps, SQDataType x)
{
	assert(ps);

	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SeqListInsert(SQ* ps, int pos, SQDataType x)
{
	SeqListCheckCapacity(ps);

	int end = ps->size;

	while (end >= pos)
	{
		ps->arr[end] = ps->arr[end - 1];
		end--;
	}

	ps->arr[pos] = x;
	ps->size++;
}

void SeqListPopFront(SQ* ps)
{
	assert(ps);
	assert(ps->size > 0);

	int start = 0;
	while (start < ps->size)
	{
		ps->arr[start] = ps->arr[start + 1];
		start++;
	}
	ps->size--;
}
void SeqListPopBack(SQ* ps)
{
	assert(ps);
	assert(ps->size > 0);

	ps->size--;
}

void SeqListErase(SQ* ps, int pos)
{
	assert(ps);
	assert(ps->size > 0);

	int start = pos;
	while (start < ps->size)
	{
		ps->arr[start] = ps->arr[start + 1];
		start++;
	}
	ps->size--;
}

void SeqListPrint(SQ* ps)
{
	assert(ps);
	assert(ps->size);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\n");
}

void SeqListModify(SQ* ps, int pos, SQDataType x)
{
	assert(pos < ps->size);

	ps->arr[pos] = x;
}
